//
//  PlayMovieViewController.m
//  OpenEye
//
//  Created by 少凯 on 16/2/26.
//  Copyright © 2016年 李少凯. All rights reserved.
//

#import "PlayViewController.h"
#import "ClassDetailModel.h"
#import "MBProgressHUD.h"
#define PLAYWIDTH self.player.view.frame.size.height
#define PLAYHEIGHT self.player.view.frame.size.width

typedef NS_ENUM(NSInteger, BoardType) {
    BoardHidden,
    BoardNoHidden
};

@interface PlayViewController ()

// 控制面板是否出现
@property (nonatomic, assign) BoardType boardType;

@property(nonatomic, strong)MPMoviePlayerController *player;

@property(nonatomic, strong)UIView *downPanel;
@property(nonatomic, strong)UIView *upPanel;
@property(nonatomic, strong)UISlider *slider;
@property(nonatomic, strong)UILabel *currentTime;//已经播放的时间
@property(nonatomic, strong)UILabel *chiefTime;//剩余时间
@property(nonatomic, strong)UILabel *titleLabel;

@property(nonatomic, strong)UIButton *PlayOrStopButton;//暂停
@property(nonatomic, strong)UIButton *BackButton;//返回上一页详情
@property(nonatomic, strong)UIButton *NextButton;//下一个视频
@property(nonatomic, strong)UIButton *LastButton;//上一个视频

@property(nonatomic, strong)NSTimer *timer;

@property(nonatomic, assign)NSInteger daley;

@property(nonatomic, strong)UIImageView *endView;
@property(nonatomic, strong)MBProgressHUD *hud;
@end

@implementation PlayViewController

-(void)viewWillAppear:(BOOL)animated{
    ClassDetailModel *model = self.movieArray[self.indexPath];
    self.titleLabel.text = model.title;
    self.currentTime.text = @"00:00";
}
- (void)viewDidDisappear:(BOOL)animated
{
    [_timer invalidate];
    _timer = nil;
    [self.player stop];
    //    [_slider removeObserver:self forKeyPath:@"value"];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark 隐藏状态栏
- (BOOL)prefersStatusBarHidden
{
    return YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.boardType = BoardNoHidden;

    
    [self createPlayer];//创建
    [self addTap];
    [self addNotification];
    [self showMBPrograssHUD];
    [self.player play];
    
}

- (void)createPlayer{
    
    // Do any additional setup after loading the view.
    
//    self.view.backgroundColor = [UIColor whiteColor];
    
//    self.player = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL URLWithString:model.playUrl]];
    /*
     常数名	说明
     M_PI	圆周率（=π）
     M_PI_2	圆周率的１/２（=π/2）
     M_PI_4	圆周率的１/４（=π/4）
     M_1_PI	=1/π
     M_2_PI	=2/π
     M_E	=e
     M_LOG2E	log_2(e)
     M_LOG10E	log_10(e)
     */
    ClassDetailModel *model = self.movieArray[self.indexPath];
    self.player = [[MPMoviePlayerController alloc]initWithContentURL:[NSURL URLWithString:model.playUrl]];
    self.player.view.frame = CGRectMake(0, 0, HEIGHT, WIDTH);
    self.player.view.transform = CGAffineTransformMakeRotation( -M_PI_2);
    self.player.view.center = CGPointMake(WIDTH / 2, HEIGHT / 2);
    self.player.controlStyle = MPMovieControlStyleNone;
    self.player.shouldAutoplay = YES;
    [self.view addSubview:self.player.view];

    
    self.downPanel = [[UIView alloc] initWithFrame:CGRectMake(0, PLAYHEIGHT - 40, PLAYWIDTH, 40)];
    self.downPanel.backgroundColor = [UIColor clearColor];
    [self.player.view addSubview:self.downPanel];
    
    self.upPanel = [[UIView alloc] initWithFrame:CGRectMake(0, 0, PLAYWIDTH, 40)];
    self.upPanel.backgroundColor = [UIColor clearColor];
    [self.player.view addSubview:self.upPanel];
    
    self.slider = [[UISlider alloc] initWithFrame:CGRectMake(55, 17, PLAYWIDTH - 110, 8)];
    self.slider.minimumTrackTintColor = [UIColor whiteColor];
    self.slider.maximumTrackTintColor = [UIColor colorWithWhite:0.5 alpha:0.5];
    [self.slider setThumbImage:[UIImage imageNamed:@"yuan"] forState:UIControlStateNormal];
    //    // slider拖动结束后触发事件.默认是YES,一直触发.
    //    self.slider.continuous = NO;
    [self.slider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
    [self.slider addTarget:self action:@selector(sliderTouchBegin) forControlEvents:UIControlEventTouchDown];
    [self.slider addTarget:self action:@selector(sliderTouchUp) forControlEvents:UIControlEventTouchUpInside];
    [self.slider addTarget:self action:@selector(sliderTouchUp) forControlEvents:UIControlEventTouchUpOutside];

    [self.downPanel addSubview:self.slider];
    
    self.currentTime = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 55, 40)];
    self.currentTime.backgroundColor = [UIColor clearColor];
    self.currentTime.textColor = [UIColor whiteColor];
    self.currentTime.textAlignment = 2;
    self.currentTime.font = [UIFont systemFontOfSize:12];
    self.currentTime.text = @"00:00";
    [self.downPanel addSubview:self.currentTime];
    
    self.chiefTime = [[UILabel alloc] initWithFrame:CGRectMake(PLAYWIDTH - 55, 0, 55, 40)];
    self.chiefTime.backgroundColor = [UIColor clearColor];
    self.chiefTime.textColor = [UIColor whiteColor];
    self.chiefTime.font = [UIFont systemFontOfSize:12];
    self.chiefTime.text = @"00:00";
    [self.downPanel addSubview:self.chiefTime];
    
    self.PlayOrStopButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.PlayOrStopButton.frame = CGRectMake(0, 0, 50, 50);
    self.PlayOrStopButton.center = CGPointMake(PLAYWIDTH / 2, PLAYHEIGHT / 2);
    self.PlayOrStopButton.backgroundColor = [UIColor clearColor];
    [self.PlayOrStopButton setImage:[UIImage imageNamed:@"playMV"] forState:UIControlStateNormal];
    [self.PlayOrStopButton addTarget:self action:@selector(PlayOrStopAction:) forControlEvents:UIControlEventTouchUpInside];
    self.PlayOrStopButton.tag = 1;
    [self.player.view addSubview:self.PlayOrStopButton];
    
    //下一首 next
    self.NextButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.NextButton.frame = CGRectMake(0, 0, 40, 40);
    self.NextButton.center = CGPointMake(PLAYWIDTH - 30, PLAYHEIGHT / 2);
    [self.NextButton setImage:[UIImage imageNamed:@"next"] forState:UIControlStateNormal];
    [self.NextButton addTarget:self action:@selector(NextAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.player.view addSubview:self.NextButton];
    
    //上一首 last
    self.LastButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.LastButton.frame = CGRectMake(0, 0, 40, 40);
    self.LastButton.center = CGPointMake(30, PLAYHEIGHT / 2);
    [self.LastButton setImage:[UIImage imageNamed:@"last"] forState:UIControlStateNormal];
    [self.LastButton addTarget:self action:@selector(LastAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.player.view addSubview:self.LastButton];
    
    self.BackButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.BackButton.frame = CGRectMake(8, 5, 40, 40);
    [self.BackButton setImage:[UIImage imageNamed:@"goback"] forState:UIControlStateNormal];
    [self.BackButton addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.upPanel addSubview:self.BackButton];
    
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 5, PLAYWIDTH, 40)];
    self.titleLabel.textColor = [UIColor whiteColor];
    self.titleLabel.font = [UIFont systemFontOfSize:15];
    self.titleLabel.backgroundColor = [UIColor clearColor];
    [self.upPanel addSubview:self.titleLabel];
}


#pragma mark 手势
-(void)addTap{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction)];
    [self.PlayOrStopButton addGestureRecognizer:tap];
    [self.player.view addGestureRecognizer:tap];
    [[self.player.view.subviews firstObject]addGestureRecognizer:tap];
}

- (void)tapAction
{
    if (self.boardType == BoardNoHidden) {
        [UIView animateWithDuration:0.5 animations:^{
            
            self.downPanel.frame = CGRectMake(0, PLAYHEIGHT, PLAYWIDTH, 40);
            self.upPanel.frame = CGRectMake(0, -40, PLAYWIDTH, 40);
            self.PlayOrStopButton.alpha = 0;
            self.PlayOrStopButton.userInteractionEnabled = NO;
            self.NextButton.center = CGPointMake(PLAYWIDTH + 10, PLAYHEIGHT / 2);
            self.LastButton.center = CGPointMake(-40, PLAYHEIGHT / 2);
            self.boardType = BoardHidden;
        }];
    }
    
    else
    {[UIView animateWithDuration:0.5 animations:^{
        
        self.downPanel.frame = CGRectMake(0, PLAYHEIGHT - 40, PLAYWIDTH, 40);
        self.upPanel.frame = CGRectMake(0, 0, PLAYWIDTH, 40);
        self.PlayOrStopButton.alpha = 1;
        self.PlayOrStopButton.userInteractionEnabled = YES;
        self.NextButton.center = CGPointMake(PLAYWIDTH - 30, PLAYHEIGHT / 2);
        self.LastButton.center = CGPointMake(30, PLAYHEIGHT / 2);
        self.boardType = BoardNoHidden;
    }];
    }
}


#pragma mark - 滑条的点击方法
-(void)sliderAction:(UISlider *)slider{
    self.currentTime.text = [self changeTimeWithSeconds:slider.value];
}
-(void)sliderTouchBegin{
    [self.player pause];
    [self.timer setFireDate:[NSDate distantFuture]];
}
-(void)sliderTouchUp{
    {
        if (self.player.duration > 0) {
            self.player.currentPlaybackTime = self.slider.value;
            self.currentTime.text = [self changeTimeWithSeconds:self.player.currentPlaybackTime];
            [self.timer setFireDate:[NSDate distantPast]];
            [self.player play];
            [self PlayOrStopAction];//滑动结束后添加点击方法
        }else{
            self.slider.value = 0;
        }
    }
}
#pragma mark 返回
//视频播放时的返回
- (void)backAction:(UIButton *)btn{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
//视频播放完毕点屏幕中央差号返回
- (void)backTap:(UITapGestureRecognizer *)tap{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
#pragma mark 播放/暂停
//正常情况下播放/暂停
-(void)PlayOrStopAction:(UIButton *)btn{
    if (self.PlayOrStopButton.tag ==1) {
        [self.player pause];
        self.PlayOrStopButton.tag = 0 ;//注意
    }
    else if (self.PlayOrStopButton.tag == 0) {
        [self.player play];
        self.PlayOrStopButton.tag = 1;
    }
}
//滑动slider结束后的第一次点击
-(void)PlayOrStopAction{
    if (self.PlayOrStopButton.tag == 1) {
        [self.player pause];
        self.PlayOrStopButton.tag = 0 ;//注意
    }
    else if (self.PlayOrStopButton.tag == 0) {
        [self.player play];
        self.PlayOrStopButton.tag = 1;
    }
}
#pragma mark 上一首 & 下一首
-(void)LastAction:(UIButton *)btn{
    [self.hud hide:YES];
    self.PlayOrStopButton.hidden = NO;//不隐藏
    if (self.indexPath == 0) {
        //最前一个视频,提示:
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"已经是第一个啦" preferredStyle:UIAlertControllerStyleAlert];
        
        [self presentViewController:alert animated:YES completion:^{
            
        }];
        
        [self dismissViewControllerAnimated:YES completion:^{
            
        }];
        NSLog(@"第一个了");
    }
    else{
        [self.player stop];
        self.indexPath -= 1;
        ClassDetailModel *model = self.movieArray[self.indexPath];
        self.titleLabel.text = model.title;
        self.player.contentURL = [NSURL URLWithString:model.playUrl];
        NSLog(@"")
        [self.player play];
    }
}
-(void)NextAction:(UIButton *)btn{
    [self.hud hide:YES];
    self.PlayOrStopButton.hidden = NO;
    if (self.indexPath == self.movieArray.count - 1 ) {
        //最后一个视频,提示:
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"已经是最后一个啦" preferredStyle:UIAlertControllerStyleAlert];
        
        [self presentViewController:alert animated:YES completion:^{
            
        }];
        
        [self dismissViewControllerAnimated:YES completion:^{
            
        }];
        NSLog(@"最后一个了,日")
    }
    else{
        [self.endView removeFromSuperview];
        //把当前view从它的父view和窗口中移除，同时也把它从响应事件操作的响应者链中移除
        [self.player stop];
        self.indexPath += 1;
        ClassDetailModel *model = self.movieArray[self.indexPath];
        self.titleLabel.text = model.title;
        self.player.contentURL = [NSURL URLWithString:model.playUrl];
        [self.player play];
    }
}

#pragma mark 添加监听
- (void)addNotification
{
    NSNotificationCenter *notification = [NSNotificationCenter defaultCenter];
    //播放状态发生改变
    [notification addObserver:self selector:@selector(mediaPlaybackStateChange:) name:MPMoviePlayerPlaybackStateDidChangeNotification object:self.player];
    //播放已经完成
    [notification addObserver:self selector:@selector(mediaPlaybackDidFinish:) name:MPMoviePlayerPlaybackDidFinishNotification object:self.player];
    //加载状态发生改变
    [notification addObserver:self selector:@selector(mediaPlayerLoadStateChange:) name:MPMoviePlayerLoadStateDidChangeNotification object:self.player];
    //获取视频总长度后, 走这个方法
    [notification addObserver:self selector:@selector(mediaplayDurationAvailable:) name:MPMovieDurationAvailableNotification object:self.player];
}
//播放状态发生改变
- (void)mediaPlaybackStateChange:(NSNotificationCenter *)notification
{
    switch (self.player.playbackState) {
        case MPMoviePlaybackStatePlaying:
            NSLog(@"正在播放");
            [self.PlayOrStopButton setImage:[UIImage imageNamed:@"pause"] forState:UIControlStateNormal];
            break;
        case MPMoviePlaybackStatePaused:
            NSLog(@"暂停播放");
            [self.PlayOrStopButton setImage:[UIImage imageNamed:@"playMV"] forState:UIControlStateNormal];
            self.PlayOrStopButton.tag = 0;
            break;
        case MPMoviePlaybackStateInterrupted:
            NSLog(@"中断播放");
            break;
        case MPMoviePlaybackStateStopped:
            NSLog(@"停止播放");
            break;
        case MPMoviePlaybackStateSeekingBackward:
            NSLog(@"向后播放");
            break;
        case MPMoviePlaybackStateSeekingForward:
            NSLog(@"向前播放");
            break;
        default:
            break;
    }
}
//播放已经完成
- (void)mediaPlaybackDidFinish:(NSNotificationCenter *)notification
{
    NSLog(@"播放完成");
    if (self.slider.value >= self.slider.maximumValue - 5) {
        
        [self createEndView];
    }
}
#pragma mark 结束界面
- (void)createEndView
{
    ClassDetailModel *model = self.movieArray[self.indexPath];
    self.endView = [[UIImageView alloc] initWithFrame:self.player.view.bounds];
    
    NSString *name = @"gif.gif";
    NSString *filePath = [[NSBundle bundleWithPath:[[NSBundle mainBundle] bundlePath]] pathForResource:name ofType:nil];
    NSData *imageData = [NSData dataWithContentsOfFile:filePath];
    UIImage *image = [UIImage sd_animatedGIFWithData:imageData];
    
    [self.endView sd_setImageWithURL:[NSURL URLWithString:model.coverForFeed] placeholderImage:image];
    [self.player.view addSubview:self.endView];
    
    UIView *blackView = [[UIView alloc] initWithFrame:self.player.view.bounds];
    blackView.backgroundColor =[UIColor blackColor];
    blackView.alpha = 0.5;
    [self.endView addSubview:blackView];
    
    self.endView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backTap:)];
    [blackView addGestureRecognizer:tap];
    
    UIImageView *backView = [[UIImageView alloc] initWithFrame:CGRectMake(50, 30, 30, 30)];
    backView.center = CGPointMake(PLAYWIDTH / 2, PLAYHEIGHT / 2 + 40);
    backView.image = [UIImage imageNamed:@"iconfont-x"];
    backView.userInteractionEnabled = YES;
    [self.endView addSubview:backView];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 30)];
    titleLabel.center = CGPointMake(PLAYWIDTH / 2, PLAYHEIGHT / 2 - 50);
    titleLabel.text = model.title;
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:20];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.endView addSubview:titleLabel];
    
    UIButton *nextBu = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    [nextBu setImage:[UIImage imageNamed:@"iconfont-ttpodicon"] forState:UIControlStateNormal];
    nextBu.center = CGPointMake(PLAYWIDTH - 50, PLAYHEIGHT / 2);
    [nextBu addTarget:self action:@selector(NextAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.endView addSubview:nextBu];
    
}
//加载状态发生改变
- (void)mediaPlayerLoadStateChange:(NSNotificationCenter *)notification
{
    switch (self.player.loadState) {
        case MPMovieLoadStateUnknown:
            
            break;
        case MPMovieLoadStatePlayable:
            NSLog(@"加载状态:可以播放");
            [self.hud hide:YES];
            self.PlayOrStopButton.hidden = NO;
            break;
        case MPMovieLoadStatePlaythroughOK:
            NSLog(@"加载状态:将自动播放");
            [self.hud hide:YES];
            self.PlayOrStopButton.hidden = NO;
            break;
        case MPMovieLoadStateStalled:
            NSLog(@"加载状态:停滞");
            break;
        default:
            break;
    }
}
//获取视频总长度后, 走这个方法
- (void)mediaplayDurationAvailable:(NSNotificationCenter *)notification
{
    self.chiefTime.text = [self changeTimeWithSeconds:self.player.duration];
    self.slider.maximumValue = self.player.duration;
    [self.timer setFireDate:[NSDate distantPast]];
    NSLog(@"播放时长%g", self.player.duration);
}

-(NSString *)changeTimeWithSeconds:(CGFloat)seconds{
    NSInteger hour = floor(seconds / 3600);
    NSInteger minutes = floor((seconds - hour * 3600) / 60);
    NSInteger s = seconds - hour *3600 - minutes * 60;
    NSString *time = @"";
    if (hour == 0) {
        time = [NSString stringWithFormat:@"%.2ld:%.2ld",(long)minutes,(long)s];
    }
    else{
        time = [NSString stringWithFormat:@"%.2ld:%.2ld:%.2ld",(long)hour,(long)minutes,(long)s];
    }
    return time;
}
#pragma mark 刷新时间
-(NSTimer *)timer{
    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeAction:) userInfo:nil repeats:YES];
        [_timer setFireDate:[NSDate distantFuture]];
    }
    return _timer;
}

-(void)timeAction:(NSTimer *)timer{
    if (self.player.duration > 0 ) {
        self.currentTime.text = [self changeTimeWithSeconds:self.player.currentPlaybackTime];
        [self.slider setValue:self.player.currentPlaybackTime animated:YES];
    }
    //自动隐藏操作栏
    if (self.boardType == BoardHidden) {
        self.daley++;
        if (self.daley == 5) {
            [self tapAction];
        }
    }
    else{
        self.daley = 0;
    }
}

- (void)showMBPrograssHUD
{
    self.PlayOrStopButton.hidden = YES;
    //小菊花
    self.hud = [[MBProgressHUD alloc] init];
    self.hud.color = [UIColor clearColor];
    self.hud.removeFromSuperViewOnHide = YES;
    [self.player.view addSubview:self.hud];
    [self.hud show:YES];
    [self.player.view insertSubview:self.hud belowSubview:self.upPanel];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
